package com.dataseek.iot.mqtt.callback;

import com.dataseek.iot.mqtt.config.MqttSub;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Value;

/**
 * ClassName:PubCallBack
 * Describe:
 * Author:DGJ
 * Data:2020/10/29 10:48
 */
@Slf4j
public class PubCallBack implements MqttCallback {

    private MqttSub mqttSub;

    public  PubCallBack(MqttSub subsribe) throws MqttException {
        this.mqttSub = subsribe;
    }

    @Override
    public void connectionLost(Throwable cause) {
        // 连接丢失后，一般在这里面进行重连
        while (true){
            try {
                //如果没有发生异常说明连接成功，如果发生异常，则死循环
                Thread.sleep(1000);
                mqttSub.init();
                break;
            }catch (Exception e){
//                e.printStackTrace();
            }
        }

    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        System.out.println("deliveryComplete---------" + token.isComplete());
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        // subscribe后得到的消息会执行到这里面
        String result = new String(message.getPayload(),"UTF-8");
        System.out.println("接收消息主题 : " + topic);
        System.out.println("接收消息Qos : " + message.getQos());
        System.out.println("接收消息内容 : " + result);
        //这里可以针对收到的消息做处理
    }
}
